﻿using LightOMator.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace LightOMator.Bluetooth
{
    static class LightConnection
    {
        public static async Task<bool> WriteColor(this BluetoothConnection connection, byte red, byte green, byte blue)
        {
            string data = "|c|" + red + "|" + green + "|" + blue;
            bool sent = await connection.WriteString(data);
            return sent;
        }

        public static async Task<bool> WriteColor(this BluetoothConnection connection, Color color)
        {
            return await WriteColor(connection, color.R, color.G, color.B);
        }

        public static async Task<bool> WriteFades(this BluetoothConnection connection, FadeCollection fades)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("|f|").Append(getModeAsChar(fades.FadeMode)).Append('|');
            builder.Append(fades.Fades.Count).Append('|');
            foreach (Fade fade in fades.Fades)
            {
                builder.Append(fade.Color.R).Append('|').Append(fade.Color.G).Append('|').Append(fade.Color.B).Append('|');
                builder.Append(fade.FadeInTimeMs).Append('|');
                builder.Append(fade.KeepOnTimeMs).Append('|');
            }

            string data = builder.ToString();
            bool sent = await connection.WriteString(data);
            return sent;
        }

        public static async Task<bool> WriteFadesKeepOnTimeMs(this BluetoothConnection connection, int keepOnTimeMs)
        {
            bool sent = await connection.WriteString("|k|" + keepOnTimeMs);
            return sent;
        }

        public static async Task<bool> WriteFadesFadeInTimeMs(this BluetoothConnection connection, int fadeInTimeMs)
        {
            bool sent = await connection.WriteString("|i|" + fadeInTimeMs);
            return sent;
        }

        private static char getModeAsChar(FadeMode fadeMode)
        {
            switch (fadeMode)
            {
                case FadeMode.DirectFade: return 'd';
                case FadeMode.NoFade: return 'n';
                case FadeMode.DarkFade: return 'b';
            }
            throw new InvalidOperationException("for FadeMode " + fadeMode);
        }
    }
}
